<template>
  <q-page class="chat-detail-page">
    <!-- 顶部导航栏 -->
    <q-header elevated class="text-white" v-if="chatInfo" :style="setTransColor()">
      <q-toolbar>
        <q-btn flat round dense icon="arrow_back" @click="goBack" />

        <q-avatar size="36px" class="q-mx-sm">
          <img v-if="chatInfo.Starter.avatar_urls.h" :src="chatInfo.Starter.avatar_urls.h" :alt="chatInfo.title" />
          <q-icon v-else name="person" size="36px" color="white" />
        </q-avatar>

        <q-toolbar-title class="chat-header-title">
          <div class="chat-title">{{ chatInfo.title }}</div>
          <div class="chat-status">{{ chatInfo.status }}</div>
        </q-toolbar-title>

        <q-btn flat round dense icon="more_vert" />
      </q-toolbar>
    </q-header>

    <!-- 聊天消息区域 -->
    <InfiniteList :load-function="loadData" data-field="messages" pagination-field="pagination" :load-params="{ id: id }"
      @load="onLoad">
      <template #default="{ data }">
        <div class="chat-messages q-pa-md">
          <q-chat-message v-for="message in data" :key="message.id" :name="message.username" text-html
            :text="[message.message_parsed]" :stamp="formatTimeDetail(message.message_date)"
            :sent="message.user_id != chatInfo.user_id"
            :avatar="message.User.avatar_urls.h ? message.User.avatar_urls.h : undefined"
            :text-color="message.user_id != chatInfo.user_id ? 'white' : 'black'"
            :bg-color="message.user_id != chatInfo.user_id ? 'primary' : ''" class="q-mb-sm">
            <!-- 图片消息显示 -->
            <template v-if="message.image" v-slot:default>
              <div class="message-image">
                <img :src="message.image" :alt="message.text[0]" class="chat-image"
                  @click="previewImage(message.image)" />
                <div v-if="message.text[0]" class="image-caption">
                  {{ message.text[0] }}
                </div>
              </div>
            </template>
          </q-chat-message>

          <!-- 正在输入指示器 -->
          <div v-if="isTyping" class="typing-indicator q-mb-md">
            <q-chat-message :name="chatInfo.title" :avatar="chatInfo.avatar">
              <q-spinner-dots size="2em" />
            </q-chat-message>
          </div>
        </div>
      </template>
    </InfiniteList>

    <transition name="fade">
      <div v-show="showMoreMenu" class="menu-backdrop-overlay" @click="hideMoreOptions"></div>
    </transition>

    <!-- 更多选项菜单 -->
    <q-slide-transition>
      <div v-show="showMoreMenu" class="more-options-panel">
        <div class="menu-content">
          <div class="menu-grid">
            <div class="menu-item" @click="selectImage">
              <q-icon name="image" size="24px" color="primary" />
              <span>图片</span>
            </div>
            <div class="menu-item" @click="takePhoto">
              <q-icon name="camera_alt" size="24px" color="primary" />
              <span>拍照</span>
            </div>
            <div class="menu-item" @click="selectFile">
              <q-icon name="attach_file" size="24px" color="primary" />
              <span>文件</span>
            </div>
          </div>
        </div>
      </div>
    </q-slide-transition>

    <!-- 底部输入框 -->
    <q-footer :style="setTransColor()">
      <q-toolbar class="input-toolbar">
        <q-btn flat round dense icon="add" @click="toggleMoreOptions"
          :class="{ 'rotated': showMoreMenu }" />

        <q-input v-model="inputMessage" ref="inputRef" dark outlined dense placeholder="输入消息..." class="input-field" autogrow
          :max-height="100" @keyup.enter="sendMessage" @focus="scrollToBottom">
          <template v-slot:append>
            <q-btn flat round dense icon="sentiment_satisfied_alt" @click="showEmojiPicker" />
          </template>
        </q-input>

        <q-btn v-if="inputMessage.trim()" round color="primary" icon="send" size="sm" class="send-btn q-ml-sm"
          @click="sendMessage" />
      </q-toolbar>
    </q-footer>

    <!-- 图片预览对话框 -->
    <q-dialog v-model="imagePreviewDialog" @hide="closeImagePreview">
      <q-card class="image-preview-card">
        <q-card-section class="q-pa-none">
          <img :src="previewImageUrl" alt="预览图片" class="preview-image" />
        </q-card-section>
        <q-card-actions align="right">
          <q-btn flat label="关闭" color="primary" @click="closeImagePreview" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useQuasar } from 'quasar'
import { getConversationsDetail } from '../utils/api'
import InfiniteList from 'src/components/InfiniteList.vue'
import { formatTimeDetail,setTransColor } from 'src/utils/common'

// Quasar 实例
const $q = useQuasar()

// 路由
const router = useRouter()
const route = useRoute()

// 响应式数据
const inputMessage = ref('')
const messages = ref([])
const isTyping = ref(false)
const scrollAreaRef = ref(null)
const inputRef = ref(null)
const showMoreMenu = ref(false)
const imagePreviewDialog = ref(false)
const previewImageUrl = ref('')

// 聊天信息
const chatInfo = ref()
const onLoad = (result) => {
  chatInfo.value = result.conversation
}

const loadData = async (page) => {
  const result = await getConversationsDetail(page)
  return result
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (scrollAreaRef.value) {
      const scrollTarget = scrollAreaRef.value.getScrollTarget()
      scrollAreaRef.value.setScrollPosition('vertical', scrollTarget.scrollHeight, 300)
    }
  })
}

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) return

  const newMessage = {
    id: Date.now(),
    text: [inputMessage.value.trim()],
    timestamp: Math.floor(Date.now() / 1000),
    sent: true
  }

  messages.value.push(newMessage)
  inputMessage.value = ''

  scrollToBottom()

  // 模拟对方正在输入
  setTimeout(() => {
    isTyping.value = true
    setTimeout(() => {
      isTyping.value = false
      // 模拟收到回复
      const replyMessage = {
        id: Date.now() + 1,
        text: ['收到！'],
        timestamp: Math.floor(Date.now() / 1000),
        sent: false
      }
      messages.value.push(replyMessage)
      scrollToBottom()
    }, 2000)
  }, 500)
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 切换更多选项菜单
const toggleMoreOptions = () => {
  showMoreMenu.value = !showMoreMenu.value
}

// 隐藏更多选项菜单
const hideMoreOptions = () => {
  showMoreMenu.value = false
}

// 选择图片
const selectImage = () => {
  hideMoreOptions()
}

// 拍照
const takePhoto = () => {
  hideMoreOptions()
}

// 预览图片
const previewImage = (imageUrl) => {
  previewImageUrl.value = imageUrl
  imagePreviewDialog.value = true
}

// 关闭图片预览
const closeImagePreview = () => {
  imagePreviewDialog.value = false
  previewImageUrl.value = ''
}

// 选择文件
const selectFile = () => {
  hideMoreOptions()
  $q.notify({
    type: 'info',
    message: '文件功能开发中...',
    position: 'top'
  })
}

// 显示表情选择器
const showEmojiPicker = () => {
  $q.notify({
    type: 'info',
    message: '表情功能开发中...',
    position: 'top'
  })
}
const id = route.params.id
</script>

<style scoped>
.chat-detail-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.chat-header-title {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.chat-title {
  font-size: 16px;
  font-weight: 500;
  line-height: 1.2;
}

.chat-status {
  font-size: 12px;
  opacity: 0.8;
  line-height: 1;
}

.chat-container {
  flex: 1;
  overflow: hidden;
}

.chat-scroll-area {
  height: 100%;
}

.chat-messages {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.typing-indicator {
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.5;
  }

  100% {
    opacity: 1;
  }
}

.input-toolbar {
  padding: 8px 16px;
  align-items: flex-end;
}

.input-field {
  flex: 1;
  margin: 0 8px;
}

.input-field :deep(.q-field__control) {
  border-radius: 20px;
}

.send-btn {
  min-width: 40px;
  height: 40px;
}

.rotated {
  transform: rotate(45deg);
  transition: transform 0.2s ease;
}

/* 更多选项菜单样式 */
.more-options-menu {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 6000;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.menu-backdrop {
  flex: 1;
  background-color: rgba(0, 0, 0, 0.3);
}

.menu-content {
  background: white;
  border-radius: 16px 16px 0 0;
  padding: 20px;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
}

.menu-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 12px;
  border-radius: 12px;
  background-color: #f5f5f5;
  cursor: pointer;
  transition: all 0.2s ease;
}

.menu-item:hover {
  background-color: #e8f4fd;
  transform: translateY(-2px);
}

.menu-item:active {
  transform: translateY(0);
  background-color: #d1ecf1;
}

.menu-item span {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

/* 图片消息样式 */
.message-image {
  display: flex;
  flex-direction: column;
  max-width: 250px;
}

.chat-image {
  width: 100%;
  max-width: 250px;
  border-radius: 8px;
  cursor: pointer;
  transition: opacity 0.2s ease;
}

.chat-image:hover {
  opacity: 0.9;
}

.image-caption {
  margin-top: 4px;
  font-size: 14px;
  color: inherit;
}

/* 图片预览样式 */
.image-preview-card {
  max-width: 90vw;
  max-height: 90vh;
}

.preview-image {
  width: 100%;
  height: auto;
  max-height: 70vh;
  object-fit: contain;
}

/* 深色主题适配 */
.body--dark .input-field :deep(.q-field__control) {
  background-color: #2a2a2a;
  color: white;
}

.body--dark .input-field :deep(.q-field__native) {
  color: white;
}

.body--dark .menu-content {
  background-color: #2a2a2a;
}

.body--dark .menu-item {
  background-color: #3a3a3a;
}

.body--dark .menu-item:hover {
  background-color: #4a4a4a;
}

.body--dark .menu-item span {
  color: #ccc;
}

/* 响应式设计 */
@media (max-width: 600px) {
  .chat-title {
    font-size: 14px;
  }

  .chat-status {
    font-size: 11px;
  }

  .input-toolbar {
    padding: 6px 12px;
  }

  .menu-content {
    padding: 16px;
  }

  .menu-grid {
    gap: 16px;
  }

  .menu-item {
    padding: 12px 8px;
  }

  .chat-image {
    max-width: 200px;
  }

  .message-image {
    max-width: 200px;
  }
}

/* 背景遮罩 */
.menu-backdrop-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 5999;
}

/* 菜单面板容器 */
.more-options-panel {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 52px;
  z-index: 6000;
}

/* 背景遮罩淡入淡出动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>